package com.mori.encrypt.spring.boot.core.algorithm.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mori.encrypt.spring.boot.core.algorithm.EncryptAlgorithm;
import com.mori.encrypt.spring.boot.core.dto.EncryptRequestDTO;
import com.mori.encrypt.spring.boot.core.util.AesEncryptUtil;
import com.mori.encrypt.spring.boot.core.util.RsaEncryptUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * <p>  AES 和 RSA 混合加密的一种方法，用RSA加密AES的秘钥，用AES秘钥加密数据本身</p>
 *
 * @author mori
 * @since 2020/9/30 9:12
 */
public class AesWithRsaEncryptAlgorithm implements EncryptAlgorithm {

	@Override
	public String encrypt(String content, String encryptKey) throws Exception {
		JSONObject body = JSONObject.parseObject(content);
		String code = body.getString("code");
		if (Objects.isNull(code)) {
			String dataJsonStr = JSONObject.toJSONString(body, SerializerFeature.WriteMapNullValue);
			String encryptData = AesEncryptUtil.aesEncrypt(dataJsonStr, encryptKey);
			JSONObject object = new JSONObject();
			object.put("data", encryptData);
			return object.toJSONString();
		}
		Object data = body.get("data");
		if (Objects.nonNull(data)) {
			String dataJsonStr = JSONObject.toJSONString(data,SerializerFeature.WriteMapNullValue);
			String encryptData = AesEncryptUtil.aesEncrypt(dataJsonStr, encryptKey);
			body.put("data", encryptData);
		}
		return body.toJSONString();
	}

	@Override
	public String decrypt(String encryptStr, String decryptKey) throws Exception {
		// AES解密
		return AesEncryptUtil.aesDecrypt(encryptStr, decryptKey);
	}

	@Override
	public String decryptRequestBody(String requestBody, String decryptKey) throws Exception {
		if (Objects.equals(requestBody, StringUtils.EMPTY)) {
			return StringUtils.EMPTY;
		}
		// 解密数据格式:{key:"用RSA加密的AES的key",data:"原始AES的key加密的数据"}
		EncryptRequestDTO requestDto = JSONObject.parseObject(requestBody, EncryptRequestDTO.class);
		// 获得RSA加密的AES的key
		String key = requestDto.getKey();
		// RSA解密出AES的原始key
		String aesKey = RsaEncryptUtil.decrypt(key, decryptKey);
		// 用AES的key解密请求数据
		requestBody = AesEncryptUtil.aesDecrypt(requestDto.getData(), aesKey);
		return requestBody;
	}
}
